/**
 * DataHelper.java
 *
 * @version 1.0
 * @author nicky.han
 */
package cn.etgps.etgps.manager;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import cn.etgps.etgps.dataEntity.DataBaseEntity;
import cn.etgps.etgps.dataEntity.Model;

/**
 * ORMLite's SqliteOpenHelper
 *
 * @author nicky.han
 */
public class DataHelper extends OrmLiteSqliteOpenHelper {
    /**
     * Save table objects
     */
    private HashMap<String, Dao<Model, Integer>> mDataDaos = null;

    /**
     * Constructor method
     */
    public DataHelper(Context context) {

        super(context, context.getFilesDir().getAbsolutePath() + "/" + DataBaseEntity.DATABASE_NAME, null,
                DataBaseEntity.DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
        try {
            Collection<Dao<Model, Integer>> collections = mDataDaos.values();
            Iterator<Dao<Model, Integer>> itLst = collections.iterator();
            while (itLst.hasNext()) {
                TableUtils.createTable(connectionSource, ((Dao<Model, Integer>) itLst.next()).getDataClass());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        if (oldVersion == newVersion) {
            return;
        }
        try {
            Collection<Dao<Model, Integer>> collections = mDataDaos.values();
            Iterator<Dao<Model, Integer>> itLst = collections.iterator();
            while (itLst.hasNext()) {
                TableUtils.dropTable(connectionSource, ((Dao<Model, Integer>) itLst.next()).getDataClass(), true);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        onCreate(db, connectionSource);
    }

    @Override
    public void close() {
        super.close();
        mDataDaos = null;
    }

    /**
     * Get all table objects
     */
    public HashMap<String, Dao<Model, Integer>> getDataDaos(List<Class<? extends Model>> cls) throws SQLException {
        if (mDataDaos == null) {
            mDataDaos = new HashMap<String, Dao<Model, Integer>>();
        }
        mDataDaos.clear();
        for (int i = 0; i < cls.size(); i++) {
            Dao<Model, Integer> dao = (Dao<Model, Integer>) this.getDao(cls.get(i));
            mDataDaos.put(cls.get(i).getName(), dao);
        }
        return mDataDaos;
    }
}
